package com.realgodo.site.service.space;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.hibernate.DefaultEntityManager;

import com.realgodo.site.entity.space.Space;
import com.realgodo.site.entity.space.SpaceCover;

@Service("spaceCoverManager")
@Transactional
public class SpaceCoverManager extends DefaultEntityManager<SpaceCover, Long> {

	@Autowired
	protected SessionFactory sessionFactory;

	public void saveSpaceCovers(Space space, List<SpaceCover> spaceCovers) {
		List<SpaceCover> olds = this.getSpaceCovers(space.getId(),
				SpaceCover.MAX_RUSULT);
		for (SpaceCover old : olds) {
			this.entityDao.delete(old.getId());
		}
		for (SpaceCover spaceCover : spaceCovers) {
			if (null != spaceCover && null != spaceCover.getPath()
					&& !"".equals(spaceCover.getPath())) {
				spaceCover.setSpace(space);
				this.entityDao.save(spaceCover);
			}
		}
	}

	public void saveSpaceCover(Space space, SpaceCover spaceCover) {
		if (spaceCover != null) {
			spaceCover.setSpace(space);
			this.entityDao.save(spaceCover);
		}
	}

	public List<SpaceCover> getSpaceCovers(Long spaceId, int maxResult) {
		Page<SpaceCover> page = new Page<SpaceCover>(maxResult);
		Criteria c = sessionFactory.getCurrentSession().createCriteria(
				SpaceCover.class);
		c.add(Restrictions.eq("space.id", spaceId));
		c.addOrder(Order.desc("id"));
		return this.entityDao.findByCriteria(page, c).getResult();
	}

	public Long getShowCoverCount(Long spaceId) {
		Session session = this.sessionFactory.getCurrentSession();
		String hql = "select count(o) from SpaceCover o where o.space.id = "
				+ spaceId;
		Query q = session.createQuery(hql);
		return (Long) q.uniqueResult();
	}
}
